<?php

namespace App\Api\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;


class BaseRequest extends \Illuminate\Foundation\Http\FormRequest
{
    // 定义统一的返回错误格式
    protected function failedValidation(Validator $validator)
    {
        throw(new HttpResponseException(response()->json([
            'code'=>422,
            'msg'=>$validator->errors(),
            'timestamp' => Carbon::now()->timestamp
        ])));
    }


    public function expectsJson()
    {

        return ($this->ajax() && ! $this->pjax() && $this->acceptsAnyContentType()) || $this->wantsJson();
    }

    /**
     * 确定当前请求是否是json请求
     *
     * @return bool
     */
    public function wantsJson()
    {

        $acceptable = $this->getAcceptableContentTypes();

        return isset($acceptable[0]) && Str::contains(strtolower($acceptable[0]), ['/json', '+json']);
    }
}
